import { ElMessageBox,ElMessage } from 'element-plus'
import callApi from '@/axios/index'

/**
 * 导入提示
 * @param file 文件
 * @param url 接口地址
 * @param params 参数
 */
export const Dataimport = async (file: any, url: string, params) => {
  return await ElMessageBox.confirm("是否删除原有数据", "系统提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(async () => {
      return await ElMessageBox.confirm("请确认是否继续?", "系统提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(async () => {
        params.deleteOld = true
        return await importcontent(file, url, params)
      });
    })
    .catch(async () => {
      return await ElMessageBox.confirm("请确认是否继续?", "系统提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(async () => {
        params.deleteOld = false
        return await importcontent(file, url, params)
      });
    });
}

/**
 * 文件流导入
 * @param file 文件
 * @param url 接口地址
 * @param params 参数
 * @param typeLiat 导入文件类型，默认xls
 * @param size 导入文件大小,默认2MB
 */
export const importcontent = (file: any, url: string, params,typeLiat?:Array=["xls","xlsx"],size?:number=2) => {
  var fileName = [];
  fileName = file.name.split(".");
  const extension=typeLiat.includes(fileName[fileName.length - 1])
  const isLtMb = file.size / 1024 / 1024 < size;
  // console.log(file, 'file');

  if (extension) {
    ElMessage({
      message: `上传模板只能是 ${typeLiat.join(',')} 等格式!`,
      type: "warning"
    });
  }
  if (!isLtMb) {
    ElMessage({
      message: `上传模板大小不能超过 ${size}MB!`,
      type: "warning"
    });
  }

  const fd = new FormData();
  fd.append("file", file);
  params && Object.keys(params).forEach((k) => {
    fd.append(k, params[k]);
  });

  return callApi({
    api: url,
    param: fd,
    config: {
      headers: {
        "Content-Type": "multipart/form-data; charset=UTF-8",
      },
    },
  }).then((res: any) => {
    console.log(res, 'res');
    return res
  })
}